/**
 * created by denglingcong 2014.12.24
 * 用于查看、编辑组织树，返回用户选中的组织节点
 */
define([
	'app',
    "resources/OrgResource",
	'services/TipsService'
], function(app) {

	var deps = ['TipsService','OrgResource',"MessageBox"];

	function directive(TipsService,OrgResource,MessageBox) {
		return {
			templateUrl: 'views/org/OrgTreeView.html',
			replace: true,
            restrict: "A",
			scope: {
				datas: "=fcOrgTreeView",  /**所有组织的数据**/
                selectedOrg : "=?",     //选中的组织对象
                onOrgSelect : "&onOrgSelect",      //选中某组织时回调
                editOrgTree : "@",          //是否带组织树编辑功能
                treeParam : "=?"
			},
			link: function($scope) {

                /*********************************初始化数据************************************/

                $scope.orgLocated = {}; // 最终定位到的组织节点
                $scope.isShow = {}; // 记录节点的输入框
                $scope.isEdit={}; // 记录节点的编辑框
                $scope.isShown = false; // 同级或根组织编辑框显示状态
                $scope.isLowerShown = false; // 下级组织编辑框显示状态
                $scope.isEditShown = false; // 组织编辑显示状态
                $scope.isNullEdit = false;
                $scope.edit={}; // 输入框里的值ֵ
                $scope.searchObj = {};   //搜索相关的数据
                $scope.selectedOrg = $scope.selectedOrg || {};     //选中的组织

                /*********************************生成组织树************************************/

                /**分组*/
                $scope.groupBy = function (list, key) {
                    var map = {};
                    for(var i = 0; i < list.length; i++) {
                        var item = list[i];
                        var items = map[item[key]];
                        if(items == null) {
                            items = [item];
                            map[item[key]] = items;
                        } else {
                            items.push(item);
                        }
                    }
                    return map;
                } ;

                $scope.toMap = function (datas) {
                    return $scope.groupBy(datas, "orgPid");
                } ;

                /**
                 * 把map结构转成树形结构 .
                 * initOrNot表示是否初始化，每个节点都控制不展开，否则，由各个节点自己控制
                 */
                $scope.toTree = function(dataMap, orgPid,initOrNot) {
                    var tree = dataMap[orgPid] || [];

                    /**这里 根节点 要排下序，集团公司在前面，合作伙伴在后面**/
                    if(orgPid == "0"){
                        tree.sort(function(a,b){
                            return a.orgType - b.orgType;
                        });
                    }

                    for(var i = 0; i < tree.length; i++) {
                        tree[i].subs = $scope.toTree(dataMap, tree[i].orgId,initOrNot);
                        if(initOrNot){
                            tree[i].isSubsShow = false;
                        }
                    }
                    return tree;
                };

                // 展开/收起组织节点
                $scope.openTree = function(org) {
                    $scope.show(false);
                    // 隐藏下级组织
                    org.isSubsShow = !org.isSubsShow;
                };

                /**
                 * 初始化树
                 */
                $scope.toInit = function() {
                    var parentMap = $scope.toMap($scope.datas);
                    $scope.orgs = $scope.toTree(parentMap, 0,true);
                    $scope.show(false);
                };

                /**加载数据**/
                /*$scope.getData = function(){
                    OrgResource.getOrgListByType($scope.treeParam.orgType).success(function (list){
                        if(list){
                            $scope.datas = list;
                            *//**初始化树*//*
                            $scope.toInit();
                            *//**默认选中第一个组织**//*
                            if($scope.orgs && $scope.orgs.length>0){
                                $scope.selectOrg($scope.orgs[0]);
                            }
                        }
                    });
                };*/
                
                
                /**加载数据**/
                $scope.getData = function(){
                    OrgResource.getOrgListByCode($scope.treeParam.companyCode).success(function (list){
                        if(list){
                            $scope.datas = list;
                            /**初始化树*/
                            $scope.toInit();
                            /**默认选中第一个组织**/
                            if($scope.orgs && $scope.orgs.length>0){
                                $scope.selectOrg($scope.orgs[0]);
                            }
                        }
                    });
                };

                $scope.getData();

                /*********************************选择某组织************************************/

                // 记录选择的组织
                $scope.selectOrg = function(org){
                    org.isSubsShow = !org.isSubsShow;
                    if ($scope.isShown || $scope.isLowerShown || $scope.isEditShown) {
                        // 如果已有输入框或编辑框在显示则不做记录
                    } else {
                        angular.extend($scope.selectedOrg,org);
                        //回调指令调用方的方法
                        if($scope.onOrgSelect){
                            $scope.onOrgSelect();
                        }
                    }
                };


                /*********************************编辑组织树************************************/

                // 显示/隐藏编辑框 type:1根2同级3下级
                $scope.show = function(isShow, type){
                    if (isShow && ($scope.isShown || $scope.isLowerShown || $scope.isEditShown)) {
                        return;
                    }

                    var selectedOrg = $scope.selectedOrg;
                    if (type == 2) {
                        if (selectedOrg) {
                            $scope.orgLocated = selectedOrg;
                            $scope.isShow[$scope.orgLocated.orgId] = isShow;
                            $scope.isShown = true;
                        } else {
                            alert("请选择一个组织");
                            return;
                        }
                    } else if (type == 3) {
                        if (selectedOrg) {
                            $scope.orgLocated = selectedOrg;
                            $scope.isShow[$scope.orgLocated.orgId] = isShow;
                            $scope.isLowerShown = true;
                        } else {
                            alert("请选择一个组织");
                            return;
                        }
                    } else if (type == 1) {
                        // 定位到最后一个根节点
                        if ($scope.orgs.length > 0) {
                            $scope.orgLocated = $scope.orgs[$scope.orgs.length - 1];
                            $scope.orgLocated.isSubsShow = false;
                            $scope.isShow[$scope.orgLocated.orgId] = isShow;
                            $scope.isShown = true;
                            $scope.isNullEdit = false;
                        } else {
                            $scope.isEmptyShown = true;
                            $scope.isNullEdit = true;
                        }
                    }

                    if(!isShow) {
                        $scope.edit.inputValue = "";
                        $scope.isShow[$scope.orgLocated.orgId] = false;
                        $scope.isEdit[$scope.orgLocated.orgId] = false;
                        $scope.isShown = false;
                        $scope.isEmptyShown = false;
                        $scope.isLowerShown = false;
                        $scope.isEditShown = false;
                        $scope.isNullEdit = false;
                    }

                };

                // 双击更新
                $scope.edit = function(org) {
                    if (!$scope.editOrgTree || $scope.isShown || $scope.isLowerShown || $scope.isEditShown) {
                        return;
                    }
                    if(org == null){
                        org = 	$scope.selectedOrg;
                        if(org == null){
                            alert("请选择一个组织");
                            return;
                        }
                    }
                    $scope.edit.inputValue = org.orgName;
                    $scope.orgLocated = org;
                    $scope.isEdit[org.orgId] = true;
                    $scope.isEditShown = true;
                };

                // 新增组织
                $scope.save = function() {
                    if ($scope.edit.inputValue) {
                        var org = {};
                        org.orgName = $scope.edit.inputValue;
                        if ($scope.isShown) {
                            org.orgPid = $scope.orgLocated.orgPid;
                        } else if ($scope.isLowerShown) {
                            org.orgPid = $scope.orgLocated.orgId;
                        } else {
                            org.orgPid = 0;
                        }
                        org.orgType = $scope.treeParam.orgType;         //要么是集团0，要么是合作伙伴1
                        OrgResource.saveOrg(org).success(function(data){
                            $scope.getData();
                            $scope.isNullEdit = false;
                        });

                    } else {
                        alert("请输入组织名称");
                    }
                };

                $scope.update = function() {
                    if ($scope.edit.inputValue) {
                        var org = {};
                        org.orgName = $scope.edit.inputValue;
                        org.orgId = $scope.selectedOrg.orgId;
                        org.orgPid = $scope.selectedOrg.orgPid;

                        OrgResource.editOrg(org.orgId,org.orgName).success(function(data){
                            $scope.getData();
                        });

                    } else {
                        alert("请输入组织名称");
                    }
                };

                //删除组织
                $scope.del = function() {
                    if ($scope.selectedOrg) {
                        //确认删除组织
                        var dialog = MessageBox.confirm("请确认!将要删除您所指定的组织以及它的下级组织");
                        dialog.result.then(function(){
                            var orgId = $scope.selectedOrg.orgId;
                            OrgResource.delOrg(orgId).success(function(data){
                                TipsService.show(data);
                                $scope.getData();
                            });
                        });
                    } else {
                        alert("删除失败");
                    }
                };

                /*********************************搜索定位组织************************************/

                //匹配关键词
                function checkKey(sourceStr){
                    return sourceStr.indexOf($scope.searchObj.searchKeyTemp) != -1;
                }

                //搜索并显示树
                function searchAndToTree(){
                    // 遍历所有组织，找到符合对应关键词的组织 ，directOrgs：直接匹配关键词的组织,这些组织要高亮显示
                    var allOrgs = angular.copy($scope.datas);
                    var directOrgs = [];
                    for(var i=0;i<allOrgs.length;i++){
                        var org = allOrgs[i];
                        //搜索组织，只需要判断组织名是否符合即可
                        if(checkKey(org.orgName)){
                            org.highlight = true;
                            directOrgs.push(org);
                        }
                    }

                    // allViewOrgs把匹配组织的上级组织都拉进来，并设置展开显示
                    $scope.orgIdMap = $scope.groupBy(allOrgs, "orgId");
                    var allViewOrgs = [];
                    for(var z=0;z<directOrgs.length;z++){
                        if(allViewOrgs.indexOf(directOrgs[z])==-1){
                            allViewOrgs.push(directOrgs[z]);
                        }
                        addParentOrg(directOrgs[z],allViewOrgs);
                    }

                    $scope.noneResult = allViewOrgs.length==0 ;

                    //重新生成树
                    var parentViewMap = $scope.toMap(allViewOrgs);
                    $scope.orgs = $scope.toTree(parentViewMap, 0,false);
                }

                //把匹配组织的上级组织都拉进来
                function addParentOrg(org,array){
                    if(org.orgPid && org.orgPid!="0"){
                        var temp = $scope.orgIdMap[org.orgPid];
                        var parentOrg = temp[0];
                        parentOrg.isSubsShow = true;
                        if(array.indexOf(parentOrg)==-1){
                            array.push(parentOrg);
                        }
                        addParentOrg(parentOrg,array);
                    }
                }

                //高亮显示
                $scope.highlight = function(node,flag) {
                    var text = node.orgName;
                    if(!text || !node.highlight){
                        return text;
                    }
                    return text.replace(new RegExp($scope.searchObj.searchKeyTemp, 'gi'), '<span class="text-match">$&</span>');
                };


                $scope.search = function(){
                    $scope.noneResult = false;
                    $scope.searchObj.searchKeyTemp = $scope.searchObj.searchKey;
                    if(!$scope.searchObj.searchKeyTemp || $.trim($scope.searchObj.searchKeyTemp)==""){
                        //回到初始状态
                        $scope.toInit();
                        return;
                    }
                    searchAndToTree();
                };

                //监控enter输入键触发搜索
                $scope.enterSearch = function($event){
                    if ($event.keyCode === 13) {
                        $scope.search();
                    }
                };


			}
		};
	}

	directive.$inject = deps;
	return app.lazy.directive('fcOrgTreeView', directive);
});